package com.bwie.MQ;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * @className: MailConsumer
 * @Description: TODO
 * @version: v1.８.0
 * @author: GONGWENXUE
 * @date: 2025/10/10 22:24
 */
@Component
@RabbitListener(queues = "business.follow.queue")
public class MailConsumer {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @RabbitHandler
    public void handleFollowRemind(Map<String, Object> msg) throws MessagingException, javax.mail.MessagingException {
        Long businessId = (Long) msg.get("businessId");
        List<Long> userIds = (List<Long>) msg.get("userIds");

        // 1. 查询用户邮箱（实际应从数据库查询）
        List<String> emails = userIds.stream()
                .map(id -> "user" + id + "@example.com")
                .toList();

        // 2. 创建富文本邮件（支持HTML）
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(emails.toArray(new String[0]));
        helper.setSubject("【商机跟进提醒】");
        helper.setText("<p>您好，商机ID：<strong>" + businessId + "</strong> 需要跟进，请及时处理。</p>", true);

        // 3. 发送邮件
        mailSender.send((MimeMessagePreparator) mimeMessage);
    }
}
